package cn.harry.cabinet.viewmodel

import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import cn.harry.cabinet.model.entity.User
import cn.harry.cabinet.repository.UserRepository
import kotlinx.coroutines.launch

/**
 * 用户ViewModel
 * 连接UI和数据仓库
 */
class UserViewModel(application: Application) : BaseViewModel(application) {
    
    private val repository = UserRepository(application)
    
    val users: LiveData<List<User>> = repository.getUsers()
    val totalCount: LiveData<Int> = repository.getTotalCount()
    
    /**
     * 检查是否还有更多数据
     */
    fun hasMoreData(): Boolean = repository.hasMoreData()
    
    /**
     * 搜索用户
     */
    fun searchUsers(query: String) {
        viewModelScope.launch {
            try {
                repository.searchUsers(query)
            } catch (e: Exception) {
                showError("搜索用户失败: ${e.message}")
            }
        }
    }
    
    /**
     * 刷新用户列表
     */
    fun refreshUsers() {
        viewModelScope.launch {
            try {
                repository.refreshUsers()
            } catch (e: Exception) {
                showError("刷新用户列表失败: ${e.message}")
            }
        }
    }
    
    /**
     * 加载更多用户数据
     */
    fun loadMoreUsers() {
        if (!hasMoreData()) return
        
        viewModelScope.launch {
            try {
                repository.loadMoreUsers()
            } catch (e: Exception) {
                showError("加载更多数据失败: ${e.message}")
            }
        }
    }
    
    /**
     * 添加新用户
     */
    fun addUser(user: User, callback: (() -> Unit)? = null) {
        showLoading()
        viewModelScope.launch {
            try {
                repository.addUser(user)
                hideLoading()
                callback?.invoke()
            } catch (e: Exception) {
                hideLoading()
                showError("添加用户失败: ${e.message}")
            }
        }
    }
    
    /**
     * 更新用户
     */
    fun updateUser(user: User, callback: (() -> Unit)? = null) {
        showLoading()
        viewModelScope.launch {
            try {
                repository.updateUser(user)
                hideLoading()
                callback?.invoke()
            } catch (e: Exception) {
                hideLoading()
                showError("更新用户失败: ${e.message}")
            }
        }
    }
    
    /**
     * 删除用户
     */
    fun deleteUser(user: User, callback: (() -> Unit)? = null) {
        showLoading()
        viewModelScope.launch {
            try {
                repository.deleteUser(user)
                hideLoading()
                callback?.invoke()
            } catch (e: Exception) {
                hideLoading()
                showError("删除用户失败: ${e.message}")
            }
        }
    }
}